<template>
  <div class="document-layout">
    <!-- 文档内容区 -->
    <main class="document-main">
      <div class="document-content">
        <!-- 面包屑导航 -->
        <a-breadcrumb class="breadcrumb">
          <a-breadcrumb-item>
            <router-link to="/">首页</router-link>
          </a-breadcrumb-item>
          <template v-if="document">
            <a-breadcrumb-item v-if="document.category">
              <router-link :to="`/category/${document.category.slug}`">
                {{ document.category.title }}
              </router-link>
            </a-breadcrumb-item>
            <a-breadcrumb-item>{{ document.title }}</a-breadcrumb-item>
          </template>
        </a-breadcrumb>

        <!-- 文档标题区 -->
        <div v-if="document" class="document-header">
          <h1 class="document-title">{{ document.title }}</h1>
          <div class="document-meta">
            <span><calendar-outlined /> {{ formatDate(document.created_at) }}</span>
            <span><eye-outlined /> {{ document.views }} 次阅读</span>
            <span v-if="document.author">
              <user-outlined /> {{ document.author.username }}
            </span>
          </div>
        </div>

        <!-- 文档内容区 -->
        <a-card class="content-card" :loading="loading">
          <div class="markdown-content" v-html="renderedContent"></div>
        </a-card>
      </div>

      <!-- 右侧目录导航 -->
      <aside class="document-toc" v-if="toc.length">
        <a-anchor :items="toc" />
      </aside>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { marked } from 'marked'
import DOMPurify from 'dompurify'
import { 
  CalendarOutlined,
  EyeOutlined,
  UserOutlined
} from '@ant-design/icons-vue'
import { getDocumentDetail, increaseDocumentViews } from '@/api/document'

const route = useRoute()
const document = ref(null)
const loading = ref(true)
const toc = ref([])

// 获取文档详情
const fetchDocument = async () => {
  loading.value = true
  try {
    const response = await getDocumentDetail(route.params.slug)
    document.value = response.data
    // 增加浏览量
    await increaseDocumentViews(route.params.slug)
    // 生成目录
    generateToc()
  } catch (error) {
    message.error('获取文档失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 渲染 Markdown 内容
const renderedContent = computed(() => {
  if (!document.value) return ''
  const html = marked(document.value.content)
  return DOMPurify.sanitize(html)
})

// 生成目录
const generateToc = () => {
  const content = document.value.content
  const lines = content.split('\n')
  const tocItems = []
  let currentLevel = 0
  
  lines.forEach(line => {
    if (line.startsWith('#')) {
      const level = line.match(/^#+/)[0].length
      const title = line.replace(/^#+\s*/, '')
      const anchor = `toc-${tocItems.length}`
      
      tocItems.push({
        key: anchor,
        href: `#${anchor}`,
        title,
        level
      })
    }
  })
  
  toc.value = tocItems
}

// 组件挂载时获取数据
onMounted(() => {
  fetchDocument()
})
</script>

<style lang="scss" scoped>
.document-layout {
  min-height: 100vh;
  padding: 24px;
  margin-top: 56px;
  background: var(--bg-color);
}

.document-main {
  max-width: 1400px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: 1fr 250px;
  gap: 24px;
}

.document-content {
  min-width: 0;
}

.breadcrumb {
  margin-bottom: 24px;
}

.document-header {
  margin-bottom: 24px;

  .document-title {
    margin: 0 0 16px;
    font-size: 32px;
    font-weight: 600;
    color: var(--text-color);
  }

  .document-meta {
    display: flex;
    gap: 24px;
    color: var(--text-color-secondary);
    font-size: 14px;

    span {
      display: flex;
      align-items: center;
      gap: 6px;
    }
  }
}

.content-card {
  border-radius: 8px;
  box-shadow: var(--card-shadow);
}

.markdown-content {
  font-size: 16px;
  line-height: 1.8;
  color: var(--text-color);

  :deep(h1) {
    font-size: 28px;
    margin: 40px 0 24px;
    padding-bottom: 12px;
    border-bottom: 1px solid var(--border-color);
  }

  :deep(h2) {
    font-size: 24px;
    margin: 36px 0 20px;
  }

  :deep(h3) {
    font-size: 20px;
    margin: 32px 0 16px;
  }

  :deep(p) {
    margin: 16px 0;
  }

  :deep(code) {
    background: var(--code-bg);
    padding: 2px 6px;
    border-radius: 4px;
    font-family: 'Fira Code', monospace;
  }

  :deep(pre) {
    background: var(--code-block-bg);
    padding: 16px;
    border-radius: 8px;
    overflow-x: auto;

    code {
      background: none;
      padding: 0;
    }
  }

  :deep(blockquote) {
    margin: 16px 0;
    padding: 8px 16px;
    border-left: 4px solid var(--primary-color);
    background: var(--quote-bg);
    color: var(--text-color-secondary);
  }

  :deep(ul), :deep(ol) {
    margin: 16px 0;
    padding-left: 24px;
  }

  :deep(li) {
    margin: 8px 0;
  }

  :deep(table) {
    width: 100%;
    margin: 16px 0;
    border-collapse: collapse;

    th, td {
      padding: 12px;
      border: 1px solid var(--border-color);
    }

    th {
      background: var(--table-header-bg);
      font-weight: 600;
    }

    tr:nth-child(even) {
      background: var(--table-row-bg);
    }
  }

  :deep(img) {
    max-width: 100%;
    height: auto;
    border-radius: 8px;
  }

  :deep(a) {
    color: var(--primary-color);
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }
}

.document-toc {
  position: sticky;
  top: 80px;
  height: calc(100vh - 104px);
  overflow-y: auto;
  padding-right: 16px;

  :deep(.ant-anchor) {
    padding-left: 0;
    
    &::before {
      display: none;
    }
  }

  :deep(.ant-anchor-link) {
    padding: 4px 0;
  }
}

@media (max-width: 1200px) {
  .document-main {
    grid-template-columns: 1fr;
  }

  .document-toc {
    display: none;
  }
}
</style> 